<template>
  <a-drawer :title="type === 0 ? '新增面试' : '编辑面试'" :width="600" :visible="visible" :body-style="{ paddingBottom: '80px' }" @close="onClose">
    <a-form :model="form">
      <a-form-item label="标题：" name="title" :style="{ marginBottom: '10px' }">
        <a-input v-model:value="form.title" placeholder="请输入面试标题" autocomplete="off" @change="change" />
      </a-form-item>

      <a-form-item label="状态：" name="status" :style="{ marginBottom: '10px' }">
        <a-space size="middle">
          <a-select ref="formRef" v-model:value="form.status" style="width: 120px" placeholder="选择状态" @change="change">
            <a-select-option :value="0">未开始</a-select-option>
            <a-select-option :value="1">进行中</a-select-option>
            <a-select-option :value="2">已结束</a-select-option>
          </a-select>
          <a-button @click="openCheckoutModal">选择招新</a-button></a-space
        >
        <span style="padding-left: 10px">选择了：{{ chosRecruitmentTitle }}</span>
      </a-form-item>

      <a-form-item label="内容：" name="information" :style="{ marginBottom: '10px' }">
        <a-textarea v-model:value="form.information" placeholder="请输入面试内容" auto-size @change="change" />
      </a-form-item>
    </a-form>
    <div class="detail">
      <p class="detail__title">面试评分细节</p>
    </div>
    <div class="detail__items">
      <div class="detail__items__item" v-for="(detail, index) in form.details" :key="index">
        <detail-item :index="index" :detail="detail" :itemLength="form.details.length" @deleteDetail="deleteDetail" @plusDetail="plusDetail" />
      </div>
    </div>
    <a-row type="flex" justify="end" class="comfirmButton">
      <a-space size="middle">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="plusInterview" v-if="type === 0">添加</a-button>
        <a-button type="primary" @click="updateInterview()" v-if="type === 1">修改</a-button>
      </a-space>
    </a-row>
  </a-drawer>
  <choose-recruitment ref="RefChilde" @chosTitle="chosTitle" :chosTitle="chosTitle" />
</template>

<script lang="ts">
import { defineComponent, Ref, ref, toRaw, watch } from 'vue'
import { message } from 'ant-design-vue'
import DetailItem from '../../../../components/DetailItem.vue'
import ChooseRecruitment from '../../../../components/ChooseRecruitment.vue'
import { post, put, detele } from '../../../../utils/request/request'

interface Detail {
  title: string
  description: string
  weight: number
  number: number | undefined
}

interface FormState {
  title: string
  information: string
  recruitment_id: number | undefined
  status: number | undefined
  details: Detail[]
}

const form: Ref<FormState> = ref({
  title: '',
  information: '',
  recruitment_id: undefined,
  status: 0,
  details: [
    {
      title: '',
      description: '',
      weight: 1,
      number: undefined
    }
  ]
})

const deleteList: Ref<number[]> = ref([])

const isChange = ref<boolean>(false)

// 调用子组件方法，打开 modal
const useCheckoutEffect = () => {
  const RefChilde = ref()
  const chosRecruitmentTitle = ref<string>('')
  const openCheckoutModal = () => {
    RefChilde.value.showModal()
  }
  return { RefChilde, chosRecruitmentTitle, openCheckoutModal }
}

// 抽屉相关逻辑
const useDrawerEffect = () => {
  const visible = ref<boolean>(false)
  const showDrawer = () => {
    visible.value = true
  }
  const onClose = () => {
    visible.value = false
    form.value = {
      title: '',
      information: '',
      recruitment_id: undefined,
      status: 0,
      details: [
        {
          title: '',
          description: '',
          weight: 1,
          number: undefined
        }
      ]
    }
  }
  return { visible, showDrawer, onClose }
}

// 添加删除按钮，子组件调用方法
const useEmitEffect = (token: string, props: any) => {
  const plusDetail = (index: number) => {
    isChange.value = true
    if (props.type === 1) {
      const newDetail = {
        title: '',
        description: '',
        weight: 1,
        number: undefined
      }
      form.value.details.splice(index + 1, 0, newDetail)
    } else if (props.type === 0) {
      const newDetail = {
        title: '',
        description: '',
        weight: 1,
        number: undefined,
        id: -1
      }
      form.value.details.splice(index + 1, 0, newDetail)
    }
  }
  const deleteDetail = async (index: number, id: number) => {
    if (id) {
      deleteList.value.push(id)
      isChange.value = true
    }
    form.value.details.splice(index, 1)
  }
  return { plusDetail, deleteDetail }
}

// 网络请求相关逻辑
const useHttpRequestEffect = (token: string, emit: any, visible: Ref<boolean>, form: Ref<FormState>) => {
  const postData = async () => {
    const postRes: any = await post('/admin/api/v1/recruitment/interview', toRaw(form.value), token)
    console.log(postRes)
    if (postRes?.status_code === 0) {
      message.success('添加成功', 3)
      emit('getData')
      visible.value = false
    } else {
      message.error('添加失败', 3)
    }
  }
  const putData = async (id: number) => {
    if (id) {
      const putRes: any = await put(`/admin/api/v1/recruitment/interview/${id}`, toRaw(form.value), token)
      if (putRes?.data?.result === 0) {
        message.success('修改成功', 3)
        emit('getData')
        visible.value = false
      } else {
        message.error('修改失败', 3)
      }
    }
  }
  return { postData, putData }
}

// 表单相关逻辑
const useFormEffect = (token: string, emit: any, visible: Ref<boolean>, props: any) => {
  const propsId = ref<number>(1)
  watch(
    () => props.chosId,
    (newVal: number, oldVal: number) => {
      propsId.value = newVal
    }
  )
  const { postData, putData } = useHttpRequestEffect(token, emit, visible, form)
  const plusInterview = () => {
    console.log(toRaw(form.value))
    let weightTotal = 0
    if (form.value.title && form.value.information && form.value.recruitment_id) {
      console.log(1)
      form.value.details.forEach((detail: Detail, index) => {
        detail.number = index + 1
        weightTotal = weightTotal + detail.weight
      })
      if (weightTotal === 10) {
        console.log(2)
        let isFilled = form.value.details.every((detail) =>
          // @ts-ignore
          Object.keys(detail).every((i) => detail[i])
        )
        if (isFilled) {
          console.log(3)
          postData()
          console.log(toRaw(form.value))
        } else {
          console.log(4)
          message.warn('细则未填写完成')
        }
      } else {
        console.log(5)
        message.warn(`权重加起来不等于10，为${weightTotal}`)
      }
    } else {
      console.log(6)
      message.warn('题头相关信息没有填写完成')
    }
  }
  const updateInterview = () => {
    console.log(toRaw(form.value))
    if (isChange.value) {
      let weightTotal = 0
      if (form.value.title && form.value.information && form.value.recruitment_id) {
        form.value.details.forEach((detail: Detail, index) => {
          detail.number = index + 1
          weightTotal = weightTotal + detail.weight
        })
        if (weightTotal === 10) {
          let isFilled = form.value.details.every((detail) =>
            // @ts-ignore
            Object.keys(detail).every((i) => detail[i])
          )
          if (isFilled) {
            if (deleteList.value.length > 0) {
              deleteList.value.forEach(async (id: number) => {
                // 进行一个一个删除
                const res: any = await detele(`/admin/api/v1/recruitment/interview/detail/${id}`, {}, token)
                if (res.status_code !== 0) {
                  message.error('删除失败')
                  visible.value = true
                } else {
                  visible.value = false
                }
              })
            }
            putData(propsId.value)
          } else {
            message.warn('细则未填写完成')
          }
        } else {
          message.warn(`权重加起来不等于10，为${weightTotal}`)
        }
      } else {
        message.warn('题头相关信息没有填写完成')
      }
    } else {
      visible.value = false
      message.info('没有修改')
    }
  }
  return { propsId, plusInterview, updateInterview }
}

export default defineComponent({
  emits: ['getData'],
  props: ['chosId', 'type', 'form'],
  components: {
    DetailItem,
    ChooseRecruitment
  },
  setup(props, { emit }) {
    const token: string = localStorage.getItem('token') as string
    const { RefChilde, chosRecruitmentTitle, openCheckoutModal } = useCheckoutEffect()
    // 获得ChooseRecruitment子组件传值
    const chosTitle = (record: { id: number; title: string }) => {
      chosRecruitmentTitle.value = record.title
      form.value.recruitment_id = record.id
    }
    const { visible, showDrawer, onClose } = useDrawerEffect()
    const { propsId, plusInterview, updateInterview } = useFormEffect(token, emit, visible, props)
    const { plusDetail, deleteDetail } = useEmitEffect(token, props)
    watch(chosRecruitmentTitle, () => {
      isChange.value = true
    })
    const change = () => {
      isChange.value = true
    }

    watch(
      () => props.form,
      (newVal, oldVal) => {
        if (newVal) {
          form.value = newVal
        } else {
          form.value = {
            title: '',
            information: '',
            recruitment_id: undefined,
            status: 0,
            details: [
              {
                title: '',
                description: '',
                weight: 1,
                number: undefined
              }
            ]
          }
        }
      }
    )

    return {
      RefChilde,
      chosRecruitmentTitle,
      openCheckoutModal,
      form,
      visible,
      showDrawer,
      plusInterview,
      updateInterview,
      onClose,
      plusDetail,
      deleteList,
      deleteDetail,
      chosTitle,
      propsId,
      change,
      isChange
    }
  }
})
</script>

<style lang="less" scoped>
.detail {
  &__title {
    font-weight: bold;
    font-size: 18px;
    text-align: center;
    padding-bottom: 5px;
    border-bottom: 1px solid #c8c8c8;
  }
  &__items {
    height: 55vh;
    overflow-y: auto;
    overflow-x: hidden;
    &__item {
      padding-top: 5px;
    }
  }
}
.comfirmButton {
  position: absolute;
  bottom: 13px;
  right: 30px;
}
// 滚动条样式
::-webkit-scrollbar {
  width: 15px;
  height: 5px;
}
</style>
